using System;
using System.Collections.Generic;

namespace PK.Broadcaster
{
	public class MessageBroadcaster
	{
		private static MessageBroadcaster _instance;

		private readonly List<object> _subscribers = new List<object>();

		public static MessageBroadcaster Instance => _instance ?? (_instance = new MessageBroadcaster());

		public void Subscribe<T>(IMessageSubscriber<T> subscriber) where T : IMessage
		{
			if (!_subscribers.Contains(subscriber))
			{
				_subscribers.Add(subscriber);
			}
		}

		public void Unsubscribe<T>(IMessageSubscriber<T> subscriber) where T : IMessage
		{
			if (_subscribers.Contains(subscriber))
			{
				_subscribers.Remove(subscriber);
			}
		}

		public void BroadcastMessage<T>(T message) where T : IMessage
		{
			foreach (object subscriber in _subscribers)
			{
				try
				{
					(subscriber as IMessageSubscriber<T>)?.OnMessageReceived(message);
				}
				catch (InvalidCastException)
				{
				}
			}
		}
	}
}
